package com.yswl.pri.picture.glide;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class ImgUtils {

    //保存文件到指定路径
    public static File saveImageToGallery(Context context, File file) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "yunshuwanli";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";

        try {
            //获得原文件流
            FileInputStream fis = new FileInputStream(file);
            File outfile = new File(appDir, fileName);
            FileOutputStream fos = new FileOutputStream(outfile);
            // 缓冲数组
            byte[] b = new byte[1024 * 8];
            while (fis.read(b) != -1) {
                fos.write(b);
            }
            //通过io流的方式来压缩保存图片
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(outfile);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

            return outfile;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}